from drf_haystack.serializers import HaystackSerializer
from rest_framework import serializers

# 创建生成导航栏的序列化器以及能够按照人气价格排序的序列化器
from goods.models import SKU
from goods.search_indexes import SKUIndex


class CategorySerializer(serializers.Serializer):
    # 手动添加需要校验的字段属性
    id = serializers.IntegerField(label='ID')
    name = serializers.CharField(label='分类')


# 在点击频道第一级分类名称的时候可以跳转回分类首页
class ChannelSerializer(serializers.Serializer):
    url = serializers.CharField(read_only=True, label="链接地址")
    category = CategorySerializer()


# 定义一个生成商品数据的序列化器
class SKUSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ['id', 'name', 'price', 'comments', 'default_image_url']


# 定义一个全局索引的序列化器返回前端指定的数据
class SKUIndexSerializer(HaystackSerializer):
    # 实例化序列化器对象
    object = SKUSerializer(read_only=True)

    class Meta:
        index_classes = [SKUIndex]
        fields = ('text', 'object')
